package com.example.generator.utils;

import com.example.generator.entity.FieldInfo;
import com.example.generator.entity.TableInfo;
import com.example.generator.entity.vo.DataxParament;
import com.example.generator.enums.GeneratorTypeEnum;
import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;

import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author：QPX
 * @date：2024-01-29-16:00
 */
@Slf4j
public class GeneratorUtil {
    private final static Configuration configuration = new Configuration(Configuration.VERSION_2_3_32);

    public static void generatorJavaCode(TableInfo table, String type) throws Exception {
        configuration.setClassForTemplateLoading(TableInfo.class, "/templates/generator/code");
        Template template = configuration.getTemplate(type);
        configuration.setDefaultEncoding("UTF-8");
        template.setOutputEncoding("UTF-8");
        StringWriter stringWriter = new StringWriter();
        Map<Object, Object> result = new HashMap<>();
        result.put("table", table);
        template.process(result, stringWriter, ObjectWrapper.BEANS_WRAPPER);
        String generatedContent = stringWriter.toString();
        if (type == GeneratorTypeEnum.JAVA_Mapper_XML.getType()) {
            try (FileWriter fileWriter = new FileWriter(table.getGeneratorUrl() + "/" + table.getGeneratorName() + ".xml")) {
                fileWriter.write(generatedContent);
            }
        } else {
            try (FileWriter fileWriter = new FileWriter(table.getGeneratorUrl() + "/" + table.getGeneratorName() + ".java")) {

                fileWriter.write(generatedContent);
            }
        }
        log.info("生成类名：{}，生成路径：{}",table.getGeneratorName(),table.getGeneratorUrl());
    }

    public static void generatorDataxJson(DataxParament dataxParament, String type,List<FieldInfo> field) throws TemplateException, IOException {
        configuration.setClassForTemplateLoading(TableInfo.class, "/templates/generator/datax");
        Template template = configuration.getTemplate(type);
        configuration.setDefaultEncoding("UTF-8");
        template.setOutputEncoding("UTF-8");
        StringWriter stringWriter = new StringWriter();
        Map<Object, Object> result = new HashMap<>();
        result.put("datax", dataxParament);
        result.put("fields", field);
        template.process(result, stringWriter, ObjectWrapper.BEANS_WRAPPER);
        String generatedContent = stringWriter.toString();
        System.out.println(generatedContent);
    }
}
